package 练习;

import java.util.Arrays;
import java.util.Scanner;

public class 查找元素 {
    public static void main(String[] args) {
        int[] array = {1, 2, 99, 9, 3, 45};
        Arrays.sort(array);//排序

        System.out.println(find(array,9));
//        二分查找
        System.out.println(Arrays.binarySearch(array,9));
        System.out.println(find1(array, 9));
    }
//二分查找
    public static int find1(int[] array,int x) {
        int left = 0;
        int right = array.length-1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (x == array[mid]) {
                return mid;
            } else if (x < array[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }

    public static int find(int[] array, int x) {
        for (int i = 0; i < array.length; i++) {
            if (array[i] == x) {
                return i;
            }
        }
        return -1;
    }
}